Letter case permutation¶
Time: O(Nx2^N); Space: O(1); easy
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create.
Example 1:
Input: S = “a1b2”
Output: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]
Example 2:
Input: S = “3z4”
Output: [“3z4”, “3Z4”]
Example 3:
Input: S = “12345”
Output: [“12345”]
Constraints:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.
[1]:
class Solution1(object):
"""
Time: O(N*2^N)
Space: O(N*2^N)
"""
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
result = [[]]
for c in S:
if c.isalpha():
for i in range(len(result)):
result.append(result[i][:])
result[i].append(c.lower())
result[-1].append(c.upper())
else:
for s in result:
s.append(c)
return list(map(''.join, result))
[4]:
sol = Solution1()
S = "a1b2"
# print(sol.letterCasePermutation(S))
assert sol.letterCasePermutation(S) == ['a1b2', 'A1b2', 'a1B2', 'A1B2']
S = "3z4"
assert sol.letterCasePermutation(S) == ["3z4", "3Z4"] or ["3Z4", "3z4"]
S = "12345"
assert sol.letterCasePermutation(S) == ["12345"]